<?php

require_once (dirname(__FILE__) . '/../prepend.php');
global $bdd;
global $logger;
/**
 * SEPA direct debit (SDD) message in XML format.
 */
require_once(dirname(__FILE__) . '/../inc/SEPA/class.SEPADirectDebitTransaction.php');
require_once(dirname(__FILE__) . '/../inc/SEPA/class.SEPAException.php');
require_once(dirname(__FILE__) . '/../inc/SEPA/class.SEPAGroupHeader.php');
require_once(dirname(__FILE__) . '/../inc/SEPA/class.SEPAMessage.php');
require_once(dirname(__FILE__) . '/../inc/SEPA/class.SEPAPaymentInfo.php');
require_once(dirname(__FILE__) . '/../inc/SEPA/class.URLify.php');
require_once("dao/FacturePonctuelleDao.php");
if ($_SESSION['niveauAuth'] <> '0') {
    $message = new SEPAMessage('urn:iso:std:iso:20022:tech:xsd:pain.008.001.02');
    $groupHeader = new SEPAGroupHeader(); // (1..1)
    $groupHeader->setMessageIdentification('SEPA-' . time()); // ID Unique
    $groupHeader->setInitiatingPartyName(PRESTATAIRE_NOM); // Nom du crediteur
    $message->setGroupHeader($groupHeader);

    $paymentInfo = new SEPAPaymentInfo(); // (1..n)
    $paymentInfo->setPaymentInformationIdentification('SEPA-' . time()); // ID Unique 
    $paymentInfo->setBatchBooking('false');
    $paymentInfo->setLocalInstrumentCode('CORE'); // Autres options: COR1, B2B
    // Type et date
    $paymentInfo->setSequenceType('OOFF');
    // CORE: FRST: +6 days, RCUR: +3 days, FNAL: +3 days, OOFF: +6 days
    // B2B: All +2 days
    $days = 6;
    do {
        $days++;
        $paymentTime = strtotime("+$days days");
    } while (!isWorkableDay($paymentTime));

    $paymentInfo->setRequestedCollectionDate(date('Y-m-d', $paymentTime));
    // Account on which payment should be recieved
    $paymentInfo->setCreditorName(PRESTATAIRE_NOM);
    $paymentInfo->setCreditorAccountIBAN(IBAN);
    $paymentInfo->setCreditorAgentBIC(BIC);
    $paymentInfo->setCreditorSchemeIdentification(ICS);

    //liste les factures
    $factures = FacturePonctuelleDao::getFacturesForSepa();
    if (empty($factures)) {
        $alert = array('message' => 'Aucune facture à ajouter au fichier SEPA', 'type' => 'warning');
        $_SESSION['alerts'][] = $alert;
        return redirect("../../lancement-facture");
    }
    foreach ($factures as $facture) {
        $totalTTC = round((float) $facture->prixHT * 1.2, 2);
        //remplace caractères spéciaux
        $clientName = str_replace('&', 'et', $facture->client->raison_social);
        // création de l'iban en retirant les espaces
        $iban = trim($facture->client->code_iban) . trim($facture->client->code_etablissement) . trim($facture->client->code_guichet) . trim($facture->client->num_compte) . trim($facture->client->rib);

        try {
            $transaction = new SEPADirectDebitTransaction(); // (1..n)
            $transaction->setEndToEndIdentification($facture->client->code_client_hto); // Vu par le débiteur
            $transaction->setInstructedAmount($totalTTC);
            $transaction->setMandateIdentification(uniqid()); // Vu par le débiteur
            $transaction->setDateOfSignature(date("Y-m-d"));
            //$transaction->setAmendmentIndicator('false');
            $transaction->setDebtorName($clientName);
            $transaction->setDebtorIban($iban);
            $transaction->setDebtorAgentBIC($facture->client->swift);
            $transaction->setRemittanceInformation("Facture " . date("d/m/Y")); // Vu par le débiteur
            $paymentInfo->addTransaction($transaction);
            $return[] = $facture->id;
        } catch (Exception $exc) {
            $logger->error('Erreur à la génération du fichier SEPA pour le client :' . $facture->client->nom . '  Message : ' . $exc->getMessage());
        }
    }
    $message->addPaymentInfo($paymentInfo);

    header('Content-type: text/xml');
    header('Content-Disposition: attachment; filename=' . date("Ymd") . '-SEPA.xml');

    //MAJ factures
    $q = 'UPDATE factures_ponctuelles SET sepa = TRUE WHERE id IN (' . implode(', ', $return) . ');';
    $requete = $bdd->prepare($q);
    $requete->execute();

    echo $message->printXML();
} else {
    redirect("home-admin");
}
?>
